<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\cloud;

use GuzzleHttp\Client as GuzzleClient;

class BaseCloud
{
    protected array $guzzleOptions = [];
    protected $baseUrl = 'http://api.dkyx.cc/';
    protected $basePath = '';
    protected $baseQuery = [];
    protected $baseData = [];


    public function __construct()
    {
        $this->baseUrl = config('hiduoke.api_app') . '/';
        $this->initialize();
    }

    public function initialize()
    {

    }

    /**
     * @param string $path
     * @param array $query
     * @param array $data
     * @return array|mixed
     */
    public function post($path = '', $query = [], $data = [])
    {
        $data = array_merge($data, $this->baseData);
        $query = array_merge($query, $this->baseQuery);
        return $this->request('post', $path, [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'json'    => $data,
            'query'   => $query
        ]);
    }

    /**
     * @param string $path
     * @param array $query
     * @return array|mixed
     */
    public function get($path = '', $query = [])
    {
        $query = array_merge($query, $this->baseQuery);
        return $this->request('get', $path, [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'query'   => $query
        ]);
    }

    /**
     * @param string $method
     * @param string $path
     * @param array $options
     * @return array|mixed
     */
    public function request($method = 'get', $path = "", $options = [])
    {
        $apiUrl = $this->baseUrl . $this->basePath . $path;
        $response = $this->getHttpClient()->$method($apiUrl, $options);
        $body = \json_decode($response->getBody()->getContents(), true);
        return $body;
    }

    /**
     * @return GuzzleClient
     */
    public function getHttpClient(): GuzzleClient
    {
        return $this->httpClient ?? new GuzzleClient($this->guzzleOptions);
    }
}
